package com.glory.dgcpcpda.activity.mfg;

import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.glory.dgcpcpda.R;
import com.glory.dgcpcpda.adapter.StationDtoAdapter;
import com.glory.dgcpcpda.base.BaseActivity;
import com.glory.dgcpcpda.callback.CustomDialogEntityCallBack;
import com.glory.dgcpcpda.entity.CpcMaterialInfoEntity;
import com.glory.dgcpcpda.entity.CpcToolInfoEntity;
import com.glory.dgcpcpda.entity.EqpInfoEntity;
import com.glory.dgcpcpda.entity.LotInfoEntity;
import com.glory.dgcpcpda.entity.StationDtoEntity;
import com.glory.dgcpcpda.entity.ToolEntity;
import com.glory.dgcpcpda.entity.ToolListEntity;
import com.glory.dgcpcpda.entity.response.BaseResponseBean;
import com.glory.dgcpcpda.utils.LotUtils;
import com.glory.dgcpcpda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_CommonCallback;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class ToolBindActivity extends BaseActivity {


    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.etToolID)
    FreeUI_ClearEditText etToolID;
    @BindView(R.id.etLotID)
    FreeUI_ClearEditText etLotID;
    @BindView(R.id.etEqpWorkID)
    FreeUI_ClearEditText etEqpWorkID;
    @BindView(R.id.etEqpWorkPosition)
    FreeUI_ClearEditText etEqpWorkPosition;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.flPositionList)
    FrameLayout flPositionList;
    @BindView(R.id.tvPosition)
    TextView tvPosition;
    @BindView(R.id.ivPositionArrow)
    ImageView ivPositionArrow;
    @BindView(R.id.rvWorksList)
    RecyclerView rvWorksList;
    private FreeUI_GeneralPop mPositionPop;
    private List<String> mPositionList;
    private LotInfoEntity lotinfo;
    private StationDtoAdapter mStationDtoAdapter;
    private String toolType;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_tool_bind;
    }

    @Override
    protected void initView() {
        tvTitle.setText("Tool绑定设备");
        mPositionList = new ArrayList<>();
        setMainLayout(llMain);
        initRecyclerView(rvWorksList, this);
        mStationDtoAdapter = new StationDtoAdapter(null);
        rvWorksList.setAdapter(mStationDtoAdapter);
        toolType="";
        etEqpWorkID.setShowSoftInputOnFocus(false);
        //隐藏键盘
        InputMethodManager imm = (InputMethodManager) getSystemService(getApplicationContext().INPUT_METHOD_SERVICE);
        //隐藏
        imm.hideSoftInputFromWindow(etEqpWorkID.getWindowToken(), 0);
        initEdit(etToolID,s->requestMaterialInfo(s));
        etEqpWorkID.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                // 获取软键盘的显示状态
                boolean isOpen=imm.isActive();
                //判断是否失去焦点
                if(!hasFocus){
                    //判断是否打开软键盘
                    if (isOpen){
                        imm.toggleSoftInput(0,InputMethodManager.HIDE_NOT_ALWAYS);
                    }
                }else{
                    //判断是否打开软键盘
                    if (isOpen){
                        //隐藏
                        imm.hideSoftInputFromWindow(etEqpWorkID.getWindowToken(), 0);
                    }
                }
            }
        });

        initEdit(etEqpWorkID, new editTextListener() {
            @Override
            public void onTextChangeListener(String s) {
                LotUtils.searchEqpInfo(s, ToolBindActivity.this, getSupportFragmentManager(), new LotUtils.netCallback<EqpInfoEntity>() {
                    @Override
                    public void onSuccess(EqpInfoEntity response) {
                        etEqpWorkPosition.setText(response.getEQUIPMENT().getLOCATION());
                        requestPositionList(s);
                    }

                    @Override
                    public void onFail(Throwable t) {
                        loadError(t,"EQPQUARY");
                    }
                });
            }
        });

        initEdit(etLotID, s -> {
            //获取lot信息
            LotUtils.searchLotInfo(ToolBindActivity.this, s, getSupportFragmentManager(), new LotUtils.netCallback<LotInfoEntity>() {
                @Override
                public void onSuccess(LotInfoEntity response) {
                    lotinfo = response;
                }

                @Override
                public void onFail(Throwable t) {
                    loadError(t, "LOTQUERY");
                }
            });
        });

    }

    private void requestPositionList(String s) {
        FreeUI_EntityCallBack<BaseResponseBean<StationDtoEntity>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<StationDtoEntity>>
                (new TypeToken<BaseResponseBean<StationDtoEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<StationDtoEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),false,getSupportFragmentManager())){
                    mPositionList.clear();
                    if (response.body().getResponse().getBody() == null) {
                        return;
                    }

                    mPositionList.addAll(response.body().getResponse().getBody().getStation());
                    mStationDtoAdapter.setNewData(response.body().getResponse().getBody().getWorks());
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<StationDtoEntity>> response) {
                super.onError(response);
                loadError(response.getException(),"GetStationByEqpId");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("EQUIPMENTID",s);
        map.addProperty("MATERIALTYPE",toolType);
        NetUtils.requestPostNet("GetStationByEqpId","GetStationByEqpId",this,map,callBack);
    }
    private void requestMaterialInfo(String mlot){
        FreeUI_EntityCallBack<BaseResponseBean<CpcToolInfoEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<CpcToolInfoEntity>>
                (new TypeToken<BaseResponseBean<CpcToolInfoEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<CpcToolInfoEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    CpcToolInfoEntity.XTool cpcToolInfoEntity = response.body().getResponse().getBody().getXTool();
                     toolType = cpcToolInfoEntity.getEAPPARAM();

                }
            }

            @Override
            public void onError(Response<BaseResponseBean<CpcToolInfoEntity>> response) {
                super.onError(response);
                System.out.println("456123");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("MLOTID",mlot);
        map.addProperty("ACTIONTYPE","QUERYBYID");
        map.addProperty("EQUIPMENTID","WB0000");
        NetUtils.requestPostNet("CPC.FINDMLOTBYID", "TRANSFERMES",this, map, callBack);
    }
    @Override
    protected void initData() {
        lotinfo = new LotInfoEntity();
    }

    @OnClick({R.id.tvBaseSubmit,R.id.flPositionList})
    public void onViewClicked(View view) {
        switch (view.getId()){
            case R.id.tvBaseSubmit:
//                if (actionControl("Submit21")){
//                    return;
//                }

                String state = lotinfo.getLOT().getSTATE();
                if("待投产".equals(state)){
                    showConfirmDialog(ToolBindActivity.this,"批次处于待投产状态");
                    return;
                }

                if (getText(etEqpWorkID).equals("") || getText(etToolID).equals("")){
                    showToast("设备号或ToolID不能为空",false);
                    return;
                }

                FreeApi_DialogUtils.getConfirmAndCancelDialog(this, "确定要提交?", new FreeUI_CommonCallback() {
                    @Override
                    public void onSuccess() {
                        FreeUI_EntityCallBack<BaseResponseBean<ToolListEntity>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<ToolListEntity>>
                                (new TypeToken<BaseResponseBean<ToolListEntity>>() {
                                }.getType(), getSupportFragmentManager(), this) {

                            @Override
                            public void onSuccess(Response<BaseResponseBean<ToolListEntity>> response) {
                                super.onSuccess(response);
                                if (response.body().isSuccess(getApplicationContext(),false,getSupportFragmentManager())){
                                    if(!response.body().getResponse().getBody().getCOMMENT().equals("")){
                                        showConfirmDialog(ToolBindActivity.this,"绑定成功，"+response.body().getResponse().getBody().getCOMMENT());
                                    }else {
                                        showConfirmDialog(ToolBindActivity.this,"绑定成功");
                                    }
//                                    showToast("绑定成功",true);
//                                    finish();
                                }
                            }

                            @Override
                            public void onError(Response<BaseResponseBean<ToolListEntity>> response) {
                                super.onError(response);
                                loadError(response.getException(),"TOOLREPORT");
                            }
                        };
                        JsonObject map = new JsonObject();
                        map.addProperty("ACTIONTYPE","UP");
                        map.addProperty("EQUIPMENTID",getText(etEqpWorkID));
                        map.addProperty("LOTID",getText(etLotID));
                        map.addProperty("SITE",tvPosition.getText().toString().equals("") ? "无" : tvPosition.getText().toString());
                        List<ToolEntity> toolList = new ArrayList<>();
                        ToolEntity toolEntity = new ToolEntity(getText(etToolID));
                        toolList.add(toolEntity);
                        map.add("TOOLLIST",new JsonParser().parse(new Gson().toJson(toolList)).getAsJsonArray());
                        NetUtils.requestPostNet("CPC.TOOLREPORT","TOOLREPORT",this,map,callBack);
                    }
                }, () -> {

                }).show(getSupportFragmentManager(),"TOOLREPORT");
                break;
            case R.id.flPositionList:

                if (mPositionList.size() <= 0){
                    showToast("未获取到站点列表",false);
                    return;
                }

                if (mPositionPop != null) {
                    if (mPositionPop.isShowing()) {
                        mPositionPop.dismiss();
                    }
                } else {
                    mPositionPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flPositionList.getWidth(), mPositionList, ivPositionArrow, (codeS, i) -> {
                        tvPosition.setText(codeS);
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivPositionArrow);
                mPositionPop.showAsDropDown(flPositionList, 0, 0);
                break;
        }

    }

}
